package zero.springdemo.springquartzdemo.core.config

import org.quartz.Trigger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.quartz.SchedulerFactoryBean
import javax.annotation.PostConstruct


@Configuration
open class QuartzConfig {

    private final val logger = LoggerFactory.getLogger(this.javaClass)

    @Qualifier("cornSchedule")
    private val factory: SchedulerFactoryBean? = null

    /**
     * 调度器工厂Bean
     */
    @Bean(name = ["schedulerFactory"])
    open fun schedulerFactory(@Qualifier("myFirstExerciseJobTrigger") myFirstExerciseJobTrigger: Trigger,
                              @Qualifier("mySecondExerciseJobTrigger") mySecondExerciseJobTrigger: Trigger): SchedulerFactoryBean {
        val bean = SchedulerFactoryBean()
        // 覆盖已存在的任务
        bean.setOverwriteExistingJobs(true)
        // 延时启动定时任务，避免系统未完全启动却开始执行定时任务的情况
        //bean.setStartupDelay(15)
        // 注册触发器
        bean.setTriggers(myFirstExerciseJobTrigger, mySecondExerciseJobTrigger)
        bean.stop()
        return bean
    }


    @Bean(name = ["cornSchedule"])
    open fun getCornSchedule(): SchedulerFactoryBean {
        val cornSchedule = SchedulerFactoryBean()
        cornSchedule.isAutoStartup = true
        cornSchedule.setSchedulerName("dynamicSchedule")
        return cornSchedule
    }

    @PostConstruct
    fun initQuartz() {
        if (factory != null) {
            factory.start()
        }
    }

}